//
//  WSJAlertController.swift
//  WSJAlertViewController
//
//  Created by macOS on 2017/4/21.
//  Copyright © 2017年 macOS. All rights reserved.
//

import UIKit


//
//不能再外部构建,只允许在内部使用
class WSJAlertController: NSObject {

    
    fileprivate var p: BuilderParams?
    
    
    private init(p: BuilderParams) {
        super.init()
        
        self.p = p
    }
    
    
    open func showController(){
        
        let alert = UIAlertController(title: p?.title, message: p?.message, preferredStyle: .alert)
        
        alert.addAction(UIAlertAction(title: p?.confirmTitle, style: .default, handler: p?.confirmHandler))
        alert.addAction(UIAlertAction(title:p?.cancelTitle, style: UIAlertActionStyle.cancel, handler: p?.cancelHandler))
        
        p?.context?.present(alert, animated: true, completion: nil)
        
        
    }
    
    

    //存取参数的私有类
    fileprivate class BuilderParams: NSObject {
        
        
        //上下文
        var context: UIViewController?
        
        var title: String?
        
        
        var message: String?
        
        var confirmTitle: String?
        
        //回调函数
        var confirmHandler: ((UIAlertAction) -> Void)?
        
        //取消按钮文本
        var cancelTitle: String?
        
        var cancelHandler: ((UIAlertAction) -> Void)?
        
       

        init(_ context: UIViewController) {
            super.init()
            self.context = context
        }
        
        
        
    }
    
    
    //构建者类
     class Builder: NSObject {
        
        fileprivate var p:BuilderParams?
        
        init(context :UIViewController) {
            
            super.init()
            self.p = BuilderParams(context);
            
        }
        
        func setTitle(_ title: String) -> Builder {
            self.p?.title = title
            return self
        }
        func setMessage(_ messgae: String) -> Builder {
            self.p?.message = messgae
            return self
        }
        
        func setConfirmTitle(_ confirmTitle: String) -> Builder {
            self.p?.confirmTitle = confirmTitle
            return self
        }
        
        // ( ()->() )? = nil 默认值为nil
        func setConfirmHandler(_ confirmHandler: ((UIAlertAction) -> Void)? = nil )-> Builder {
            self.p?.confirmHandler = confirmHandler
            return self
        }
        
        func setCancelTitle(_ cancelTitle: String) -> Builder {
            self.p?.cancelTitle = cancelTitle
            return self
        }
        
        func setCancelHandler(_ cancelHandler: ((UIAlertAction) -> Void)? = nil )-> Builder {
            self.p?.cancelHandler = cancelHandler
            return self
        }
        
        func builder() -> WSJAlertController? {
            
            return WSJAlertController(p: self.p!)
        }
        
        
    }
    
   
    
}
